package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.StudentInfoEntity;
import com.jeeplus.test.jlnu.admissionInfo.service.ExcelServiceStu;
import com.jeeplus.test.postgraduate.domain.vo.PostgraduateReqVo;

import java.util.ArrayList;
import java.util.List;

public class StudentInfoDataListener extends AnalysisEventListener<PostgraduateReqVo> {

    private final ExcelServiceStu excelServiceStu;
    private final ProgressCallback progressCallback;
    private static final int BATCH_COUNT = 500;
    private final String officeId;
    private List<PostgraduateReqVo> dataList = new ArrayList<>();
    private int totalRecords;
    private int currentRecords;
    private final String importType;

    private int templateId2;
    private final String templateInfoType;



    public StudentInfoDataListener(ExcelServiceStu excelServiceStu, ProgressCallback progressCallback,
                                   int totalRecords,String officeId,String importType,String templateInfoType,int templateId1) {
        this.excelServiceStu = excelServiceStu;
        this.progressCallback = progressCallback;
        this.totalRecords = totalRecords;
        this.officeId = officeId;
        this.importType = importType;
        this.templateInfoType = templateInfoType;
        this.templateId2 = templateId1;
    }

    @Override
    public void invoke(PostgraduateReqVo data, AnalysisContext context) {
        // 获取当前行号
        int currentRow = context.readRowHolder().getRowIndex();

        // 判断当前是否是第二行，跳过第二行
//        if (currentRow == 1) {
//            return; // 跳过第二行
//        }
        data.setOfficeId(officeId);
        dataList.add(data);
        currentRecords++;

        if (dataList.size() >= BATCH_COUNT) {
            saveDataToDatabase();
            dataList.clear();
        }

        updateProgress();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!dataList.isEmpty()) {
            saveDataToDatabase();
            dataList.clear();
        }
        updateProgress();
    }

    private void saveDataToDatabase() {
        if (!dataList.isEmpty()) {
            excelServiceStu.insertDataStu(dataList,importType,templateInfoType,officeId,templateId2);
        }
    }

    private void updateProgress() {
        int progress = (int) (((double) currentRecords / totalRecords) * 100);
        progressCallback.onProgress(progress);
    }

    public interface ProgressCallback {
        void onProgress(int progress);
    }
}
